package com.main;

import java.util.HashMap;
import java.util.Iterator;

import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.ServiceContext;

import com.searchingmodule.RecommendingElement;
import com.searchingmodule.SearchingElement;
import com.util.Validator;

public class ServiceInterface {
	
	
	private RecommendingElement recommendingElement;
	private SearchingElement searchingElement;
	private SearchingElement sElement;
	private RecommendingElement rElement;
	private String[] REMOVABLE_CHARS={",","\\?","\\.","\"","-","/","\\+","=","-","<","`","~","!","#","&","\\*"};
	/*session handling part*/
	public static final String COUNT = "count";
    public void init(ServiceContext serviceContext) {
           serviceContext.setProperty(COUNT, new Integer(-1));
           // initialize the count to zero   serviceContext.setProperty(COUNT, new Integer(-1));
           try{
               ServiceClient sc=new ServiceClient();
               sc.engageModule("addressing");
               }
           catch (Exception e) {
               // TODO: handle exception
           }

    }
	public void destroy(ServiceContext serviceContext) {
		System.out.println("Destroying the service context");
	}
	public int getCount() {
	    ServiceContext serviceContext = MessageContext.getCurrentMessageContext().getServiceContext();
	    Integer storedVaue = (Integer) serviceContext.getProperty(COUNT);
	    int newCount = storedVaue.intValue() + 1;
	    serviceContext.setProperty(COUNT, new Integer(newCount));
	    return newCount;
	}/*session handling part*/
	
	public void login(String apiKey,String service) throws Exception
	{
		Factory factory=new Factory();
		sElement=factory.getSearchingElement(apiKey, service);
	}
	
	/*Context Based Image Search
	/*Service-get 10 recommended images and 10 from Google*/
	public String searchImages(String keyword,String contextString,String apiKey) throws Exception {
		Validator.validateInput(keyword, contextString, apiKey,"");
		keyword=keyword.toLowerCase();
		contextString=contextString.toLowerCase();
		if(contextString.contains("tags:")){
			int index=contextString.indexOf("tags:");
			if(index==0){
				for (String c : REMOVABLE_CHARS) {
					contextString=contextString.replaceAll(c, " ");
				}
			}
		}
		contextString=contextString.trim();
		System.out.println("**************   "+contextString);
		if(sElement==null)
			login(apiKey,"S1");
		sElement.setKeyword(keyword);
	//String imageURLs=TestServiceInterface.getResult();
		String imageURLs=null;
		
		sElement.isUserBased=false;	
		
		int count =getCount();
		//imageURLs=rElement.recommendedImages(keyword,getContextMap(contextString),getCount());
				
		imageURLs=sElement.getRecommendedImages(keyword,getContextMap(contextString),count);
		
		return imageURLs;
	}
	/*Service-get 10 recommended images and 10 from Google- user based*/
	public String searchUsedBasedImages(String keyword,long userID,String contextString,String apiKey) throws Throwable {
		System.out.println("Before Validator");
		Validator.validateInput(keyword, contextString, apiKey, ""+userID);
		keyword=keyword.toLowerCase();
		contextString=contextString.toLowerCase();
		if(contextString.contains("tags:")){
			int index=contextString.indexOf("tags:");
			if(index==0){
				for (String c : REMOVABLE_CHARS) {
					contextString=contextString.replaceAll(c, " ");
				}
			}
		}
		contextString=contextString.trim();
		if(sElement==null)
			login(apiKey,"S2");
		String imageURLs=null;
		sElement.isUserBased=true;
		sElement.setKeyword(keyword);
		sElement.setUserID(userID);
		int count=getCount();
	   //int count=0;
		//imageURLs=element.recommendedImages(keyword,getContextMap(contextString),getCount());
		imageURLs=sElement.geRecommendedImages(keyword, userID, getContextMap(contextString), count);
		//	System.gc();
		
		sElement.datamodel.finalize();
	
		return imageURLs;
	}//Context Based Image Search7
	
	
	/*Context Based Image Recommenation*/
	//Service-get n  recommendations-userbased
	public String getRecommendations(String keyword,long userID,String contextString,String apiKey) throws Exception {
		
		login(apiKey,"S2");
		String imageURLs=null;
		rElement.isUserBased=true;
		imageURLs=rElement.getRecommendedImages(userID, keyword, getContextMap(contextString));
			
		return imageURLs;
	}
	
	//Service-get n  recommendations
	public String getRecommendations(String keyword,String contextString,String apiKey) throws Exception {
		
		login(apiKey,"S2");
		String imageURLs=null;
		rElement.isUserBased=true;
		imageURLs=rElement.getRecommendedImages(keyword, getContextMap(contextString));
			
		return imageURLs;
	}
	/*Context Based Image Recommenation*/

	
	
	//save user feed back after calling searchImages(Request request) method
	public int saveFeedback(String url){
		
		
		int i=0;
		try {
			i=sElement.saveUserFeedback(url);
		} catch (Exception e) {
			i=-1;
			e.printStackTrace();
		}
		
		return i;
	}
	
	//save user feed back after calling getRecommendations
	/*public int saveFeedback(long imageID){
		
		
		int i=0;
		try {
			i=rElement.saveUserFeedback(imageID);
		} catch (Exception e) {
			i=-1;
			e.printStackTrace();
		}
		
		return i;
	}
	*/
	
	
	/*Feed from their own database*/
	//feed the picSEEK database from their own images by providing context details and ImageID*/
	public int feedPicSEEK(String keyword,String contextString,String apiKey,long imageID){
		
		int i=0;
		try {
			i=rElement.saveUserFeedback(imageID, keyword, getContextMap(contextString));
			
		} catch (Exception e) {
			i=-1;
			e.printStackTrace();
		}
		return i;
	}
	
	//feed the picSEEK database from their own images by providing context details and ImageID with userID*/
	public int feedPicSEEK(String keyword,long userID,String contextString,String apiKey,long imageID){
		
		int i=0;
		try {
			i=rElement.saveUserFeedback(userID, imageID, keyword, getContextMap(contextString));
			
			
		} catch (Exception e) {
			i=-1;
			e.printStackTrace();
		}
		return i;
	}
	/*Feed from their own database*/


	
	//construct a contextMap from the contextString
	private HashMap<String, String> getContextMap(String contextString)
	{
		String tempStr=contextString;
		System.out.println(tempStr);
		String[] temp=tempStr.trim().split(",");
		String temparry[]=null;
		HashMap<String, String> contextMap=new HashMap<String, String>();	
		for(int i=0;i<temp.length;i++){
			temparry=temp[i].trim().split(":");
			contextMap.put(temparry[0].trim(),temparry[1].trim());
		}
		return contextMap;
		
	}
	public ServiceInterface() {
		setSearchingElement(new SearchingElement());
		setRecommendingElement(new RecommendingElement());
	}
	public void setRecommendingElement(RecommendingElement recommendingElement) {
		this.recommendingElement = recommendingElement;
	}
	public RecommendingElement getRecommendingElement() {
		return recommendingElement;
	}
	public void setSearchingElement(SearchingElement searchingElement) {
		this.searchingElement = searchingElement;
	}
	public SearchingElement getSearchingElement() {
		return searchingElement;
	}
	
	
		
}
